package com.hjqjl.module_choice.widget.dialogfragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

/**
 * 使用方法示例，在activity中：
 * DialogAlertFragment newFragment = DialogAlertFragment.newInstance2("我是title", "我是内容", "确定");
 * newFragment.show(getSupportFragmentManager(), "dialog");
 */
//AlertDialog
public class DialogAlertFragment extends DialogFragment {
    private Context mContext;
    private DialogInterface.OnClickListener positiveOnClickListener;
    private DialogInterface.OnClickListener negativeOnClickListener;

    private DialogAlertFragment(DialogInterface.OnClickListener positiveOnClickListener, DialogInterface.OnClickListener negativeOnClickListener) {
        this.positiveOnClickListener = positiveOnClickListener;
        this.negativeOnClickListener = negativeOnClickListener;
    }

    public static DialogAlertFragment newInstance(String title, String message, String positiveStr, String negativeStr, DialogInterface.OnClickListener positiveOnClickListener, DialogInterface.OnClickListener negativeOnClickListener) {
        DialogAlertFragment frag = new DialogAlertFragment(positiveOnClickListener, negativeOnClickListener);
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putString("message", message);
        args.putString("positiveStr", positiveStr);
        args.putString("negativeStr", negativeStr);
        frag.setArguments(args);
        return frag;
    }

    //进行了简化，比如单纯通知类消息使用
    public static DialogAlertFragment newInstance2(String title, String message, String positiveStr) {
        return DialogAlertFragment.newInstance(title, message, positiveStr, "", null, null);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Bundle args = getArguments();
        String title = "";
        String message = "";
        String positiveStr = "";
        String negativeStr = "";
        if (args != null) {
            title = args.getString("title");
            message = args.getString("message");
            positiveStr = args.getString("positiveStr");
            negativeStr = args.getString("negativeStr");
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);//getActivity()报警告有可能是null，所以用mContext
        builder.setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveStr, positiveOnClickListener)
                .setNegativeButton(negativeStr, negativeOnClickListener);
        return builder.create();
    }
}